<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>生成器</title>
</head>
<body>
    <script>
        //生成器:可以自动的创建自己的迭代器

        /***
         * 自定义生成器
        */

        //对象生成器
        var obj = {
            name:"ck"
            ,age:18
            ,sex:"male"
            ,*[Symbol.iterator](){
                let keys = Object.keys(this);
                while(keys.length>0){
                    //yield 暂存一个生成器
                    yield this[keys.shift()];
                }
            }
        };
        let iterator = function(target){
            let gen = target[Symbol.iterator](),result;
            //调用生成器的next()，可见generator有自己的迭代器
            while(!(result = gen.next()).done){
                console.log(result)
            }
        }
        iterator(obj);

        //函数生成器
        var obj = {name:"ck",age:12,sex:'male'}
        let iteratorFn = function* (obj){
            let keys = Object.keys(obj);
            while(keys.length>0){
                //yield 暂存一个生成器
                yield obj[keys.shift()];
            }
        }
        let gen = iteratorFn(obj);
        iterator(gen);

        //yield* 将生成器交个另一个生成器或迭代器
        function* itFn(){
            //yield 只能用在generator（生成器）中
            yield* ["陈康",18,"国防科技"]
        }
        let it = itFn();
        console.log(it.next())//{value: "陈康", done: false}
        console.log(it.next())//{value: 18, done: false}
        console.log(it.next())//{value: "国防科技", done: false}
    </script>
</body>
</html>